package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 前端登录验证 --- 验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        //接收参数
        log.info("收到的手机号为: {}", phone);

        if (phone != null && phone.length() != 0) {
            //生成一个验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("phone: {},code: {}", phone, code);
            //服务器要储存
            //这个手机号对应的验证码
           // session.setAttribute(phone, code);

            redisTemplate.opsForValue().set(phone, code,300, TimeUnit.SECONDS);

            //客户要收到 发送短息验证码
            try {
                //SMSSendCode.sendCode(phone,code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.success(code);
        }

        return R.error("手机哈不存在，请重新输入");
    }

    /**
     * 前端登录验证
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) {
        log.info("登录的信息为: {}", user);
        String phone = user.getPhone();
        String code = user.getCode();

        //判断登陆成功
        //验证码必须要和session中的一致
        //String sessionCode = (String) session.getAttribute(phone);

        Object sessionCode = redisTemplate.opsForValue().get(phone);

        if (!code.equals(sessionCode)) {
            log.info("你输入的验证码错误");
            return R.error("你输入的验证码错误");
        }

        //判断手机号在数据库中是否存在，如果不存在就注册一个
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User one = userService.getOne(lqw);
        //判断是否存在
        if (one == null) {
            log.info("手机号尚未注册，正在注册");
            user.setStatus(1);
            user.setName("顾客_" + phone);
            userService.save(user);
            //这里判断one为null所以，把user的值赋给它
            one = user;
        }

        //登录 - 往session中存入数据
        session.setAttribute("empId", one.getId());

        //清理redis code缓存
        redisTemplate.delete(phone);

        return R.success(one);
    }

    /**
     * 修改用户个人信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody User user) {
        log.info("修改的信息为: {}", user);

        //把数据更新
        userService.updateById(user);

        //把修改后的数据返回
        User userLater = userService.getById(user);
        return R.success(userLater);
    }

    /**
     * 前端退出
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        //退出，去掉session里面的数据
        session.removeAttribute("empId");

        return R.success(null);
    }
}
